<template>
  <div>
    <div style="margin: 10px 0;">
      <el-row type="flex" class="row-search" >
        <el-col :span="2"><el-button @click="toggleSelection()" style="margin-left: 10px;">取消全选</el-button></el-col>
        <el-col :span="4"><el-input v-model="roleName" style="float:left; margin-left: 10px;  width: 200px;" suffix-icon="el-icon-search" placeholder="请输入用户名："></el-input></el-col>
        <el-col :span="2"><el-button type="primary" style="margin-left: 10px;" icon="el-icon-search" @click="load">搜索</el-button></el-col>
        <el-col :span="1"><el-button type="warning"  icon="el-icon-search" @click="reset">重置</el-button></el-col>
      </el-row>
    </div>

    <div style="margin: 10px 0; ">
      <el-row type="flex" class="row-update" >
        <el-col :span="2"><el-button type="success"  size="medium" style=" margin: 10px;" icon="el-icon-circle-plus-outline" @click="handleAdd">新增</el-button></el-col>
        <el-popconfirm
            style="margin-left: 5px;"
            confirm-button-text='确定'
            cancel-button-text='取消'
            icon="el-icon-info"
            icon-color="red"
            title="您确定执行批量删除吗？"
            @confirm="bathDel()"
        >
          <el-button slot="reference" type="danger"   size="medium" style="margin: 10px;" icon="el-icon-delete" > 批量删除</el-button>
        </el-popconfirm>
<!--        <el-col :span="2">
          <el-upload>
            <el-button action='http://localhost:9090/user/import'  type="primary"  size="medium" style="margin: 10px;" icon="el-icon-bottom"> 导入</el-button>
          </el-upload>
        </el-col>
        <el-col :span="2"><el-button type="primary"  size="medium" style="margin: 10px;" icon="el-icon-top" @click="exp"> 导出</el-button></el-col>-->
      </el-row>
    </div>

    <el-table
        :header-cell-style="{ background: '#F2F2F2', color: '#333' }"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="角色ID"  show-overflow-tooltip/>
      <el-table-column prop="roleName" label="角色名" show-overflow-tooltip/>
      <el-table-column prop="description" label="描述" show-overflow-tooltip/>
      <el-table-column prop="flag" label="唯一标识" show-overflow-tooltip/>
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button type="warning" @click="selectMenu(scope.row.id)" icon="el-icon-circle-plus" size="mini">分配菜单</el-button>
          <el-button type="primary" @click="handleEdit(scope.row)" icon="el-icon-edit" size="mini">修改</el-button>
          <el-popconfirm
              style="margin-left: 5px;"
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除该条消息吗？"
              @confirm="handleDel(scope.row.id)"
          >
            <el-button type="danger" slot="reference" icon="el-icon-delete" size="mini">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px;">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[3, 6, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="新增角色" :visible.sync="dialogFormVisible" width="30%">
      <el-form label-width="80px">
<!--        <el-form-item label="角色ID" :label-width="formLabelWidth">
          <el-input v-model="form.id" autocomplete="off"></el-input>
        </el-form-item>-->
        <el-form-item label="角色名" >
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色名" >
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色标识">
          <el-input v-model="form.flag" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="11"><el-button @click="dialogFormVisible = false" style="align-content: center">取 消</el-button></el-col>
          <el-col :span="6"><el-button type="primary" @click="save">确 定</el-button></el-col>
        </el-row>
      </div>
    </el-dialog>

    <el-dialog title="菜单分配" :visible.sync="menuDialogVis" width="25%">
      <el-tree
          :props="props"
          :data="menuData"
          node-key="id"
          show-checkbox
          :default-expanded-keys="expends"
          :default-checked-keys="checks"
          ref="tree"
          @check-change="handleCheckChange">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span><i :class="data.icon"/>&nbsp;{{ data.menuName }}</span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button  @click="menuDialogVis = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
export default {
  name: "Role",
  data(){
    return{
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 3,
      roleName: '',
      multipleSelection: [],
      collapseBtnClass: 'el-icon-s-unfold',
      input: '',
      dialogFormVisible: false,
      form: {},
      formLabelWidth: '60px',
      menuDialogVis: false,
      menuData: [],
      props: {
        label: 'menuName'
      },
      expends:[],
      checks: [],
      roleId: 0,
    }
  },
  created() {
    this.load()
  },
  methods:{
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    load(){
      this.request.get("/role/page",{
        params: {
          pageNum:  this.pageNum,
          pageSize: this.pageSize,
          roleName: this.roleName,
        }
      }).then(res => {
        /*console.log(res)*/
        this.tableData = res.data.records
        this.total = res.data.total
      })


    },
    reset(){
      //重置搜索框
      this.roleName = ""
      this.load()

    },
    handleAdd(){
      //新增
      this.dialogFormVisible = true
      this.form = {}
    },
    //保存
    save(){
      this.request.post("/role/save",this.form)
          .then(res => {
            //若果返回结果为true
            if(res.code === '200'){
              this.$message.success("保存成功")
              this.dialogFormVisible = false
            }else {
              this.$message.error("保存失败")
            }
          })
    },
    //编辑
    handleEdit(row){
      this.form = row
      this.dialogFormVisible = true
    },
    handleDel(id){
      this.request.delete('/role/' + id).then(res => {
        if(res.code === '200'){
          this.$message.success("删除成功")
          this.load()
        }else {
          this.$message.error("删除失败")
        }
      })
    },
    handleSelectionChange(val) {
      console.log(this.multipleSelection)
      this.multipleSelection = val
    },
    //批量删除
    bathDel(){
      //map键值对绑定multipleSelection中的id值  [{},{},{}] => [multipleItem.1.id,..2.id,..3.id,..4]
      let ids = this.multipleSelection.map(v => v.id)
      this.request.post("/role/bath/del",ids).then(res => {
        if(res.code === '200'){
          this.$message.success("批量删除成功")
          this.load()
        }else {
          this.$message.error("批量删除失败")
        }
      })
      console.log(ids)
    },

    handleSizeChange(pageSize){
      this.pageSize = pageSize
      console.log(pageSize)
      this.load()
    },
    handleCurrentChange(pageNum){
      this.pageNum = pageNum
      console.log(pageNum)
      this.load()
    },
    selectMenu(roleId){
      this.menuDialogVis = true
      this.roleId = roleId
      //请求菜单数据
      this.request.get("/menu",{
        //默认值为空
        params: {
          menuName: "",
        }
      }).then(res => {
        /*console.log(res)*/
        this.menuData = res.data

        //后台返回的id处理成id数据，传递到默认打开的expends数组中
        this.expends = this.menuData.map(v => v.id)
      })

        this.request.get("/role/roleMenu/" + roleId).then(res => {
        /*查看role的包含的menuids*/
        /*console.log(res)*/
        //拆roleid对应的menuid,赋值给
        //后台返回的id处理成id数据，传递到默认打开的expends数组中
        this.checks = res.data

        this.request.get("/menu/ids").then(res => {
          const mIds = res.data
          mIds.forEach(id => {
            if(!this.checks.includes(id)){
              /*this.@nextTick(() => {

              })*/
              console.log("id")
              this.$refs.tree.setChecked(id,false)
            }
          })
        })

      })
    },
    saveRoleMenu() {
      /*.concat(this.$refs.tree.getHalfCheckedKeys())*/
      this.request.post("role/roleMenu/" + this.roleId,this.$refs.tree.getCheckedKeys())
          .then(res => {
            if(res.code === '200'){
              this.$message.success("绑定成功")
              this.menuDialogVis = false;
              this.$store.commit("logout")
              /*this.load()*/
            }else {
              this.$message.error(res.msg)
            }
          })
    },
    handleCheckChange(data, checked, indeterminate){
      /*console.log(data, checked, indeterminate);*/
    }
  }

}
</script>

<style scoped>
.el-header {
  background-color: #ffffff;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
</style>